package demo.jackson;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.TypeIdResolver;
import com.fasterxml.jackson.databind.type.SimpleType;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ServiceLoader;

import demo.jackson.impl.Payload;

/**
 *
 */
public class IdResolver implements TypeIdResolver {

    private JavaType javaType;

    @Override
    public void init(JavaType javaType) {
    }

    @Override
    public String idFromValue(Object o) {
        return idFromValueAndType(o, o.getClass());
    }

    @Override
    public String idFromValueAndType(Object o, Class<?> aClass) {
        String value = null;
        try {
            Field field = aClass.getDeclaredField(Payload.PAYLOAD_FILED_NAME);
            field.setAccessible(true);
            Object payload = field.get(o);
            if (payload != null && JacksonInterface.class.isAssignableFrom(payload.getClass())) {
                Type type = payload.getClass().getAnnotation(Type.class);
                if (type != null) {
                    value = type.value();
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return value;
    }

    @Override
    public String idFromBaseType() {
        return idFromValueAndType(null, this.javaType.getClass());
    }

    @Override
    public JavaType typeFromId(DatabindContext databindContext, String s) throws IOException {
        ServiceLoader<JacksonInterface> jacksonInterfaces = ServiceLoader.load(JacksonInterface.class);
        return this.javaType;
    }

    @Override
    public String getDescForKnownTypeIds() {
        return null;
    }

    @Override
    public JsonTypeInfo.Id getMechanism() {
        return JsonTypeInfo.Id.CUSTOM;
    }
}
